<template>
  <div class="aid">
    <div class="base">
      <p>{{ JSON.stringify(text)=='{}'?'新增来电':showType==0?'来电详情':'修改来电' }}
        <a-icon @click="closeFunction(false)" class="closeCircle" type="close-circle" />
      </p>
      <div class="bg-cover" v-if="showType==0"></div>
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <div class="scrollView">
          <a-form-model-item label="接听时间" prop="AnswerTime">
            <a-date-picker show-time format="YYYY-MM-DD HH:mm:ss" v-model="form.AnswerTime" style="width: 100%;"
                           @change="onChange"
            />
          </a-form-model-item>
          <a-form-model-item label="接听人" prop="AnswerUserID">
            <a-select show-search option-filter-prop="children" :filter-option="filterOption" v-model="form.AnswerUserID" :allowClear="true"
                      @change="answerUser"
            >
              <a-select-option v-for="(item, index) in userList" :key="index" :value="item.ID">{{ item.Name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="来电号码" prop="Phone">
            <a-input v-model="form.Phone" :allowClear="true" @blur="checkPhone"/>
          </a-form-model-item>
          <a-form-model-item label="来电人姓名" prop="Name">
            <a-input v-model="form.Name" :allowClear="true"/>
          </a-form-model-item>
          <a-form-model-item label="性别" prop="Sex">
            <a-radio-group v-model="form.Sex">
              <a-radio :value="1">
                男
              </a-radio>
              <a-radio :value="2">
                女
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="问题描述" prop="Content">
            <a-input v-model="form.Content" :allowClear="true" type="textarea" :auto-size="{ minRows: 4, maxRows: 6 }"/>
          </a-form-model-item>
          <a-form-model-item label="问题类型" prop="QuestionID">
            <a-select v-model="form.QuestionID" @change="questionChange">
              <a-select-option v-for="(item, index) in questionList" :key="item.ID">{{ item.Name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="部门" prop="DepartID">
            <a-select v-model="form.DepartID" show-search option-filter-prop="children" :filter-option="filterOption" @change="departChange">
              <a-select-option v-for="(item, index) in departList" :key="index" :value="item.ID">{{ item.DepartName }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="部门负责人" class="ChargeUserID">
            <a-select v-model="form.ChargeUserID" show-search option-filter-prop="children" :filter-option="filterOption">
              <a-select-option v-for="(item, index) in chargeUseruserList" :key="index" :value="item.UserID">{{ item.Name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="item.FieldName" v-for="(item,index) in questions" class="icon-f" :class="{mustIcon:item.IsMust =='true'}">
            <a-input v-if="item.Type==1" placeholder="数字" v-model="item.Num" :allowClear="true"/>
            <a-date-picker v-if="item.Type==2" placeholder="日期" v-model="item.Dates" style="width: 100%;"/>
            <a-time-picker v-if="item.Type==3" :default-value="moment(item.Time?item.Time:'00:00:00', 'HH:mm:ss')" @change="changeMoment" style="width: 100%;"/>
            <a-date-picker v-if="item.Type==4" placeholder="日期加时间" v-model="item.Content" show-time format="YYYY-MM-DD HH:mm:ss"
                           style="width: 100%;"
            />
            <a-input v-if="item.Type==5" placeholder="单行文本" v-model="item.Text" :allowClear="true"/>
            <a-input v-if="item.Type==6" placeholder="多行文本" v-model="item.Textarea" :allowClear="true" type="textarea"
                     :auto-size="{ minRows: 4, maxRows: 6 }"
            />
            <a-select v-if="item.Type==7" placeholder="省份" v-model="item.Province" :allowClear="true" @change="provinceChange">
              <a-select-option v-for="(item, index) in provinceList" :key="item.ID" :value="item.ID">{{ item.ProvinceName }}</a-select-option>
            </a-select>
            <a-select v-if="item.Type==8" placeholder="市区" v-model="item.City" :allowClear="true">
              <a-select-option v-for="(item, index) in cityList" :key="item.ID">{{ item.CityName }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <a-form-model-item label="" :wrapper-col="{ offset: 5 }" v-if="showType == 1">
          <el-button type="success" size="medium" class="btn2" @click="handleSubmit(2)">
            {{ JSON.stringify(text)=='{}'?'确定并开始分配':'分配' }}
          </el-button>
          <el-button type="success" size="medium" class="btn2" @click="handleSubmit(1)">
            {{ JSON.stringify(text)=='{}'?'保存':'确认修改' }}
          </el-button>
          <el-button size="medium" style="margin-left: 10px;" @click="closeFunction(false)">
            取消
          </el-button>
        </a-form-model-item>
      </a-form-model>
    </div>
  </div>
</template>

<script>
	import {
		addAnswer,
		getDistributionUserList,
		getProvinceList,
		getCityByProvinceIDList,
		getQuestionType,
		getQuestionDepart,
		// getQuestionDepartUser,
		getQuestionVirtualField,
		updateAnswer,
		getDepartList,
		getQuestionDetail,
		getDepartUserList
	} from '@/api/follow'
	import moment from 'moment'
	export default {
		props: {
			text: Object,
			showType: Number
		},
		watch: {
			text: function(text) {
				if (JSON.stringify(text) === '{}') {
					this.questions = []
					this.form.Phone = ''
					this.form.Name = ''
					this.form.Sex = ''
					this.form.Content = ''
					this.form.QuestionID = ''
					this.form.DepartID = ''
					this.form.VirtualData = ''
					this.form.AnswerTime = this.getNowTime()
					this.form.AnswerUserID = JSON.parse(localStorage.getItem('user')).id
				} else {
					this.form = text
					this.questionChange(this.form.QuestionID)
					setTimeout(() => {
					    this.departChange(this.form.DepartID, 1)
							this._getQuestionDetail(text.ID)
					}, 1100)
				}
			}
		},
		data() {
			return {
				msg: 0,
				userList: [],
				nodeList: [],
				questionList: [],
				departList: [],
				chargeUseruserList: [],
				questions: [],
				provinceList: [],
				cityList: [],
				formLayout: 'horizontal',
				CenterDropdownList: [],
				QuestionName: '',
				ChargeUserName: '',
				Time: '',
				form: {
					AnswerTime: '',
					AnswerUserID: JSON.parse(localStorage.getItem('user')).id,
					Phone: '',
					Name: '',
					Sex: '',
					Content: '',
					QuestionID: '',
					DepartID: '',
					VirtualData: '',
					ChargeUserID: ''
				},
				rules: {
					AnswerTime: [{
						required: true,
						message: '请选择接听时间',
						trigger: 'blur'
					}],
					AnswerUserID: [{
						required: true,
						message: '请选择接听人',
						trigger: 'blur'
					}],
					Phone: [{
						required: true,
						message: '请输入来电号码',
						trigger: 'blur'
					}],
					Name: [{
						required: true,
						message: '请输入来电人姓名',
						trigger: 'blur'
					}],
					Sex: [{
						required: true,
						message: '请输入来电人性别',
						trigger: 'blur'
					}],
					Content: [{
						required: true,
						message: '请输入问题描述',
						trigger: 'blur'
					}],
					QuestionID: [{
						required: true,
						message: '请选择问题类型',
						trigger: 'blur'
					}],
					DepartID: [{
						required: true,
						message: '请选择部门',
						trigger: 'blur'
					}]
				},
				timeString: '',
				isSubmit: true,
				departList1: []
			}
		},
		created() {
			setTimeout(() => {
			    this._getProvinceList()
			    this._getDistributionUserList()
			}, 600)
			// this.form.AnswerTime = this.getNowTime()
		},
		methods: {
			moment,
			closeFunction(flag) {
				this.$emit('closeFun', flag)
			},
			filterOption(input, option) {
				return (
					option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
				)
			},
			answerUser(ID) {
				this.form.AnswerUserID = ID
			},
			checkPhone() {
				if (!(/^1[3|4|5|6|7|8][0-9]\d{8,8}$/.test(this.form.Phone))) {
						this.$message.error('手机号码有误！')
						this.form.Phone = ''
						return false
				}
			},
			async _getQuestionDetail(id) {
				this.questions = []
				let detail = await getQuestionDetail({ID: id})
				let field = detail.data.field
				let fieldData = detail.data.fieldData
				if (fieldData.length > 0) {
					field.forEach((item, index) => {
						fieldData.forEach((val, i) => {
							if (item.ID === val.FieldID) {
								if (item.Type === 7) {
									this.provinceChange(val.Content)
								}
								let show = item.Type == 1 ? 'Num' : item.Type == 2 ? 'Dates' : item.Type == 3 ? 'Time' : item.Type == 4 ? 'Content' : item.Type == 5 ? 'Text' : item.Type == 6 ? 'Textarea' : item.Type == 7 ? 'Province' : 'City'
								this.questions.push({ID: item.ID, FieldName: item.FieldName, IsMust: item.IsMust, Errormsg: item.Errormsg, Type: item.Type, Regex: item.Regex, [show]: (item.Type == 7 || item.Type == 8) ? parseInt(val.Content) : val.Content})
							}
						})
					})
				}
			},
			changeMoment(time, timeString) {
				this.timeString = timeString
			},
			getNowTime() {
			    let date = new Date()
					let year = date.getFullYear()
					let month = date.getMonth()
					let day = date.getDate()
			    return `${year}-${(month + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
			},
			async _getDistributionUserList() {
				let res = await getDistributionUserList()
				this.userList = res.data.data
				let question = await getQuestionType()
				this.questionList = question.data.data
			},
			async _getProvinceList() {
				let res = await getProvinceList({appKey: 'C23DQW'})
				this.provinceList = res.data.data
			},
			async questionChange(ID) {
				this.form.QuestionID = ID
				let data = {}
				data.questionID = ID
				let depart = await getQuestionDepart(data)
				let departList = []
				depart.data.data.forEach(item => {
					departList.push({ID: item.DepartID, DepartName: '「推荐」' + item.DepartName})
				})
				let depart1 = await getDepartList()
				this.departList1 = depart1.data.data
				departList.forEach(item => {
					let index = this.departList1.findIndex(d => d.ID === item.ID, 1)
					this.departList1.splice(index, 1)
				})
				this.departList = departList.concat(this.departList1)
				if (JSON.stringify(this.text) === '{}') {
					this.form.DepartID = this.questionList[0].DepartID || (depart.data.data.length > 0 ? depart.data.data[0].DepartID : '')
				}
				if (this.form.DepartID) {
					this.departChange(this.form.DepartID, 2)
				}
				let questions = await getQuestionVirtualField(data)
				questions.data.data.forEach(item => {
					item.Content = '',
					item.Province = '',
					item.City = '',
					item.Num = '',
					item.Dates = '',
					item.Time = '',
					item.Text = '',
					item.Textarea = ''
				})
				this.questions = questions.data.data
			},
			async departChange(value, type) {
				// let ID = this.departList.filter(data => data.DepartID === value)[0].ID
				// let data = {}
				// data.questionDepartID = ID
				let depart = await getDepartUserList({departID: value})
				this.chargeUseruserList = depart.data.data
				if (JSON.stringify(this.text) === '{}') {
					console.log(this.questionList[0].DepartIDList[0].UserList.UserID)
					this.form.ChargeUserID = this.questionList[0].DepartIDList[0].UserList[0].UserID || (depart.data.data.length > 0 ? depart.data.data[0].UserID : '')
				}
			},
			async provinceChange(ID) {
				let city = await getCityByProvinceIDList({appKey: 'C23DQW', provinceID: ID})
				this.cityList = city.data.data
			},
			departFocus() {
				if (!this.form.QuestionID) {
					this.$message.error('请先选择问题类型')
				}
			},
			chargeUserFocus() {
				if (!this.form.DepartID) {
					this.$message.error('请先选择问题类型和部门')
				}
			},
			onChange(value, dateString) {
				let beginDate = new Date(this.getNowTime())
				let endDate = new Date(value)
				if (endDate <= beginDate) {
					  this.form.AnswerTime = dateString
						return true
				}
				this.form.AnswerTime = ''
				this.$message.error('接听时间不能超过当前时间')
				return false
			},
			// 时间戳转年月日
			formatDate(newdate, type) {
			  var date = new Date(newdate)
			  var YY = date.getFullYear() + '-'
			  var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
			  var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
			  var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
			  var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
			  var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
				let time = ''
				if (type === 1) {
					time = YY + MM + DD + ' ' + hh + mm + ss
				} else if (type === 2) {
					time = YY + MM + DD + ''
				} else {
					time = hh + mm + ss
				}
			  return time
			},
			handleSubmit(e) {
				this.isSubmit = true
				this.questions.forEach(item => {
					if (item.IsMust === 'true' && ((!item.Content && item.Type === 4) || (!item.Province && item.Type === 7) || (!item.City && item.Type === 8) || (!item.Num && item.Type === 1) || (!item.Dates && item.Type === 2) || (!item.Time && item.Type === 3) || (!item.Text && item.Type === 5) || (!item.Textarea && item.Type === 6))) {
						this.$message.error(item.FieldName + '不能为空')
						this.isSubmit = false
					} else {
						switch (item.Type) {
						 case 1:
								if (item.Regex && !new RegExp(item.Regex).test(item.Num)) {
									this.$message.error(item.Errormsg)
									this.isSubmit = false
								}
								break
						 case 5:
								if (item.Regex && !new RegExp(item.Regex).test(item.Text)) {
									this.$message.error(item.Errormsg)
									this.isSubmit = false
								}
								break
						 case 6:
								if (item.Regex && !new RegExp(item.Regex).test(item.Textarea)) {
									this.$message.error(item.Errormsg)
									this.isSubmit = false
								}
								break
						}
					}
				})
				if (!this.isSubmit) {
					return false
				}
				let VirtualData = []
				this.questions.forEach(item => {
					if (item.Type === 3) {
						item.Time = this.timeString
					}
					VirtualData.push(item.ID + '|' + ((item.Content ? this.formatDate(item.Content, 1) : '') || item.Province || item.City || item.Num || (item.Dates ? this.formatDate(item.Dates, 2) : '') || (item.Time ? item.Time : '') || item.Text || item.Textarea))
				})
				this.form.VirtualData = VirtualData.join(',')
				this.$refs.ruleForm.validate(async valid => {
					if (valid) {
						delete this.form.AddTime
						delete this.form.AddUserName
						delete this.form.AnswerUserName
						delete this.form.ChargeUserName
						delete this.form.DepartName
						delete this.form.QuestionName
				   this.form.State = e
						let res = {}
						if (this.text.ID) {
							res = await updateAnswer(this.form)
						} else {
							res = await addAnswer(this.form)
						}
						this.$message.success(res.data.msg)
						if (res.data.code === 1) {
							setTimeout(() => {
									this.closeFunction(true)
							}, 1000)
						}
					} else {
						console.log('error submit!!')
						return false
					}
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.mustIcon{
		/deep/.ant-form-item-label{
			label{
				&::before{
					display: inline-block;
					margin-right: 4px;
					color: #f5222d;
					font-size: 14px;
					font-family: SimSun, sans-serif;
					line-height: 1;
					content: '*';
				}
			}
		}
	}
	.bg-cover{
		background: rgba(0,0,0,0);
		position: absolute;
		left: 0;
		top: 50%;
		margin-top: -330px;
		width: 100%;
		height: 80%;
		z-index: 999999;
		display: none;
	}
	.icon-f{
		position: relative;
	}
	.icon-cc{
		position: absolute;
		left: -94px;
		top: -33px;
		font-weight: bold;
		color: #f5222d;
	}
	.row {
		display: flex;
		justify-content: space-around;
		margin-top: 15px;
	}

	.aid {
		position: fixed;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		top: 0px;
		left: 0px;
		z-index: 999;
	}
	.scrollView{
		width: 100%;
		height: 500px;
		overflow-y: auto;
	}
	.base {
		position: fixed;
		width: 600px;
		height: 640px;
		background: #fff;
		left: 50%;
		top: 50%;
		margin-left: -300px;
		margin-top: -320px;
		overflow-y: hidden;
		border-radius: 8px;
		/deep/.ant-form-item {
			margin: 20px 30px 10px 20px;
			/deep/.ant-form-item-label {
				margin-right: 10px;
				width: 110px;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				text-align: right !important;
			}

			/deep/.ant-form-item-control-wrapper {
				flex: 1;
			}
		}
	}

	.base p {
		padding: 20px 0 0 20px;
		font-size: 16px;
		.closeCircle{
			font-size: 22px;
			float: right;
			margin-right: 18px;
		}
	}

	.subnav {
		margin-left: 60px;
		height: 46px;
		display: flex;
	}

	.subnav p {
		width: 100px;
		text-align: right;
	}

	.subnav input {
		width: 300px;
		height: 30px;
		border: 1px solid #DAD9DC;
		margin-left: 20px;
	}

	.ant-form-item {
		margin-bottom: 10px;
	}
</style>
